//
//  ListNode.hpp
//  Node
//
//  Created by zhangjikuan on 2020/12/11.
//  Copyright © 2020 hsgd. All rights reserved.
//

#ifndef ListNode_hpp
#define ListNode_hpp

#include <stdio.h>

class MyListForward {
private:
    struct ListNode {
        int val;
        ListNode *next;
        ListNode(int x) : val(x), next(NULL) {}
    };

    ListNode *head;

public:
   
    
    MyListForward():head(nullptr){}
    // 1.获得链表中第index个节点的值
    int get(int index){
        int i = 0;
        ListNode *p = head;
        while (p&&i<index) {
            p = p->next;
            i++;
        }
        if (p) return p->val;
        else return -1;
    }

    // 2. 在链表头部插入一个值val的节点
    void addAtHead(int val) {
        ListNode *p = new ListNode(val);
        p->next = head;
        head = p;
    }
    
    // 3. 在链表尾部插入一个val 的节点
    void addAtTail(int val) {
        ListNode *p = new ListNode(val);
        if (head == nullptr) {
            head = p;
            return;
        }
        
        ListNode *q = head;
        
        while (q->next) {
            q = q->next;
        }
        q->next = p;
    }
    
    // 4.在索引为Index的节点之前添加置为val的节点
    void addAtIndex(int index, int val) {
        ListNode *node = new ListNode(val);
        if (index <= 0) {
            node->next = head;
            head = node;
            return;
        }
        int i = 0;
        ListNode *p = head;
        while (p && i<index -1) {
            p = p->next;
            ++i;
        }
        
        if (p) {
            node->next = p->next;
            p->next = node;
        }
        
    }
    
    // 5.删除索引为index的节点
    void deleteAtIndex(int index) {
        if (index==0 && head != nullptr) {
            ListNode *del = head;
            head = head->next;
            delete del;
            return;
        }
        
        int i = 0;
        ListNode *p = head;
        while (p && i < index - 1) {
            p = p->next;
            i ++;
        }
        
        if (!p) return;
        
        if (p->next) {
            ListNode *del = p->next;
            p->next = del->next;
            delete del;
        }
    }
    
    // 6. 链表长度
    int length(){
        int i = 0;
        ListNode *p = head;
        while (p) {
            i++;
            p=p->next;
        }
        return i;
    }
    
    
    ///7. 清空链表
    void clear(){
        ListNode *del = nullptr;
        while (head) {
            del = head;
            head = head->next;
            delete del;
        }
    }
    
    /// 删除某个节点
    void deleteNode(ListNode *node) {
        node->val = node->next->val;
        node->next = node->next->next;

    }
    
    
};




#endif /* ListNode_hpp */
***
